package com.sky.service.admin.impl;

import com.github.pagehelper.Constant;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.admin.DishFlavorMapper;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealDishMapper;
import com.sky.mapper.admin.SetmealMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.pojo.SetmealDish;
import com.sky.result.PageResult;
import com.sky.service.admin.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @Description DishServiceImpl
 * @Author lyh
 * @Date 2024-09-21
 */
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 清理缓存数据
     * @param pattern
     */
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }
    /**
     * 新增菜品
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)//设置事务，保证一块添加
    public void save(DishDTO dto) {
        //拷贝属性，只拷贝属性名相同的
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.save(dish);
        //回显id，获取id的值
        Long id = dish.getId();
        //获取风味
        List<DishFlavor> flavors = dto.getFlavors();
        if(flavors.size()>0 && flavors!=null){
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
            }
            dishFlavorMapper.saveMore(flavors);
        }
        cleanCache("dish:categoryId:"+dto.getCategoryId());
        cleanCache("dishVo:categoryId:"+dto.getCategoryId());
    }

    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Page<DishVO> page=dishMapper.pageQuery(dto);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<Long> ids) {
        // 起售中的菜品不能删除
       Integer num= dishMapper.countByStatus(ids, StatusConstant.ENABLE);
       if(num>0){
           throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
       }
        //被套餐关联的菜品不能删除
        Integer count=setmealMapper.countByDishIds(ids);
        if(count>0){
            throw  new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        dishMapper.delete(ids);
        dishFlavorMapper.deleteByDishId(ids);
        cleanCache("dish:categoryId:*");
        cleanCache("dishVo:categoryId:*");
    }

    /**
     * 根据id查询菜品
     * @param dishId
     * @return
     */
    @Override
    public DishVO getById(Long dishId) {
        return dishMapper.getById(dishId);
    }

    /**
     * 修改菜品
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto,dish);
        dishMapper.update(dish);
        Long id = dish.getId();
        dishFlavorMapper.deleteByDishId(Arrays.asList(id));
        List<DishFlavor> flavors = dto.getFlavors();
        if(flavors.size()>0 && flavors!=null){
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
            }
            dishFlavorMapper.saveMore(flavors);
        }
        cleanCache("dish:categoryId:*");
        cleanCache("dishVo:categoryId:*");
    }
    /**
     * 启用禁用菜品
     * @param status
     * @param id
     * @return
     */
    @Override
    public void updateStatus(Integer status, Long id) {
        //菜品停售，则包含菜品的套餐同时停售。
        List<SetmealDish> setmealDishes = setmealDishMapper.getByDishId(id);
        if(setmealDishes!=null && setmealDishes.size()>0){
            for (SetmealDish setmealDish : setmealDishes) {
                Long setmealId = setmealDish.getSetmealId();
                setmealMapper.stopOrStart(StatusConstant.DISABLE,setmealId);
            }
        }
        dishMapper.updateStatus(status,id);
        cleanCache("dish:categoryId:*");
        cleanCache("dishVo:categoryId:*");
    }
    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        List<Dish> list= (List<Dish>) redisTemplate.opsForValue().get("dish:categoryId:"+categoryId);
        if(list!=null && list.size()>0){
            System.out.println("redis");
            return list;
        }

        list=new ArrayList<>();
        list=dishMapper.list(categoryId, StatusConstant.ENABLE);
        redisTemplate.opsForValue().set("dish:categoryId:"+categoryId,list);
        return list;
    }
    /**
     * 根据分类id查询菜品及口味
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> list1(Long categoryId) {
        List<DishVO> list= (List<DishVO>) redisTemplate.opsForValue().get("dishVo:categoryId:"+categoryId);
        if(list!=null && list.size()>0){
            System.out.println("redis");
            return list;
        }
        list=new ArrayList<>();
       list= dishMapper.list1(categoryId, StatusConstant.ENABLE);
        redisTemplate.opsForValue().set("dishVo:categoryId:"+categoryId,list);
        return list;
    }
}